const http = require('http');
const fs = require('fs');
const path = require('path');

// 创建一个模拟的音频文件用于测试
function createTestAudioFile() {
    const testFilePath = path.join(__dirname, 'test-audio.mp3');
    // 创建一个简单的文本文件作为测试音频文件
    const testContent = 'This is a test audio file content for demonstration purposes.';
    fs.writeFileSync(testFilePath, testContent);
    return testFilePath;
}

function createMultipartData(songName, artistName, filePath) {
    const boundary = '----WebKitFormBoundary' + Math.random().toString(16);
    const fileContent = fs.readFileSync(filePath);
    const fileName = path.basename(filePath);

    let body = '';
    
    // 歌名字段
    body += `--${boundary}\r\n`;
    body += `Content-Disposition: form-data; name="songName"\r\n\r\n`;
    body += `${songName}\r\n`;
    
    // 原唱字段
    body += `--${boundary}\r\n`;
    body += `Content-Disposition: form-data; name="artistName"\r\n\r\n`;
    body += `${artistName}\r\n`;
    
    // 音频文件字段
    body += `--${boundary}\r\n`;
    body += `Content-Disposition: form-data; name="audio"; filename="${fileName}"\r\n`;
    body += `Content-Type: audio/mpeg\r\n\r\n`;
    
    const bodyBuffer = Buffer.concat([
        Buffer.from(body, 'utf8'),
        fileContent,
        Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8')
    ]);
    
    return {
        body: bodyBuffer,
        contentType: `multipart/form-data; boundary=${boundary}`
    };
}

function makeUploadRequest(data, contentType) {
    return new Promise((resolve, reject) => {
        const options = {
            hostname: 'localhost',
            port: 3001,
            path: '/api/upload/complete',
            method: 'POST',
            headers: {
                'Content-Type': contentType,
                'Content-Length': data.length
            }
        };

        const req = http.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                try {
                    const jsonBody = body ? JSON.parse(body) : {};
                    resolve({ status: res.statusCode, data: jsonBody, body });
                } catch (e) {
                    resolve({ status: res.statusCode, data: null, body });
                }
            });
        });

        req.on('error', reject);
        req.write(data);
        req.end();
    });
}

async function testCompleteUpload() {
    console.log('🎵 测试完整音频上传功能...');
    
    try {
        // 创建测试音频文件
        console.log('\n📁 创建测试音频文件...');
        const testFilePath = createTestAudioFile();
        console.log('测试文件创建成功:', testFilePath);

        // 准备上传数据
        const songName = '我的测试歌曲-' + Date.now();
        const artistName = '我的测试歌手-' + Date.now();
        
        console.log('\n📤 准备上传数据...');
        console.log('歌名:', songName);
        console.log('原唱:', artistName);

        const { body, contentType } = createMultipartData(songName, artistName, testFilePath);
        
        // 执行上传
        console.log('\n🚀 执行上传请求...');
        const uploadResult = await makeUploadRequest(body, contentType);
        
        console.log('上传结果:', uploadResult);

        // 清理测试文件
        fs.unlinkSync(testFilePath);
        console.log('\n🧹 清理测试文件完成');
        
        if (uploadResult.status === 200 && uploadResult.data?.success) {
            console.log('\n✅ 上传测试成功！');
            console.log('新增歌曲ID:', uploadResult.data.data?.songId);
            console.log('歌手ID:', uploadResult.data.data?.singerId);
        } else {
            console.log('\n❌ 上传测试失败');
        }

    } catch (error) {
        console.error('❌ 测试失败:', error);
    }
}

testCompleteUpload().then(() => {
    console.log('\n🏁 完整上传测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});